﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.UI.WebControls;
using System.Web.UI;
using umbraco.cms.businesslogic.web;
using umbraco.cms.businesslogic.propertytype;
using System.Web;
using Umbraco.Forms.Core;
using umbraco.cms.businesslogic.member;

namespace ContourStrikesAgain.Controls
{
    public class MemberPropertyMapper: WebControl, INamingContainer {

        public DropDownList picker = new DropDownList();
        public Panel p_items = new Panel();

        private Form m_Form;
        private Umbraco.Forms.Core.Attributes.Setting m_Setting;

        private Dictionary<string, string> m_recordFields;

        private Dictionary<string, DropDownList> m_fields = new Dictionary<string, DropDownList>();
        private Dictionary<string, TextBox> m_texts = new Dictionary<string, TextBox>();

        public MemberPropertyMapper(Umbraco.Forms.Core.Attributes.Setting setting, Form form)
        {
            m_Form = form;
            m_Setting = setting;

            EnsureChildControls(); 
        }

        private string _value = "";
        private Dictionary<string, string[]> _valueArray;
        public string Value {
            get {

                _value = picker.SelectedValue + "|";
                
                foreach (KeyValuePair<string, DropDownList> kv in m_fields) {
                    _value += kv.Key + ",";
                    
                    if (!string.IsNullOrEmpty(m_texts[kv.Key].Text))
                        _value += m_texts[kv.Key].Text.Replace("|", "&#124;").Replace(",", "&#44;") + ",|";
                    else if(kv.Value.SelectedValue != "__setValue")
                        _value += "," + kv.Value.SelectedValue + "|";
                }

                return _value;
            }
            set {
                _value = value;

                _valueArray = new Dictionary<string, string[]>();

                foreach (string s in _value.Split('|')) {

                    string[] arr = s.Split(',');

                    if (arr.Length == 3) {
                        string[] vals = new string[2];
                        vals[0] = arr[1];
                        vals[1] = arr[2];

                        _valueArray.Add(arr[0].Trim(), vals);

                    }

                }
            } 
            
            }

        protected override void CreateChildControls() {
            base.CreateChildControls();

            Control parent;
            Control container;
                       
            UpdatePanel up = new UpdatePanel();
            container = up.ContentTemplateContainer;
            parent = up;
           
            //Doctype picker
            picker = (DropDownList)new Umbraco.Forms.Core.FieldSetting.Pickers.MemberType().RenderControl(m_Setting, m_Form);
            picker.AutoPostBack = true;
            picker.SelectedIndexChanged += new EventHandler(picker_SelectedIndexChanged);
            picker.ID = "doctypepicker";

            //Record fields
            m_recordFields = new Dictionary<string, string>();
            foreach (Field fi in m_Form.AllFields) {
                m_recordFields.Add(fi.Id.ToString(), fi.Caption);
            }
            

            p_items.CssClass = "docMapper";
            p_items.Visible = false;

            container.Controls.Add(picker);
            container.Controls.Add(p_items);

            Controls.Add(parent);
        }


        protected override void OnLoad(EventArgs e)
        {
            base.OnLoad(e);


            //System.Web.UI.Page page = (System.Web.UI.Page)HttpContext.Current.Handler;
            ////System.Web.UI.ScriptManager.RegisterClientScriptInclude(page, page.GetType(), "fieldmapperJS", "scripts/umbracoforms.documentmapper.js");
            //page.ClientScript.RegisterClientScriptInclude(
            //    "ContourStrikesAgain.Resources.Scripts.memberPropertyMapper.js",
            //    page.ClientScript.GetWebResourceUrl(page.GetType(), "ContourStrikesAgain.Resources.Scripts.memberPropertyMapper.js"));

            Page.ClientScript.RegisterClientScriptInclude(
                "ContourStrikesAgain.Resources.Scripts.memberPropertyMapper.js",
               Page.ClientScript.GetWebResourceUrl(Page.GetType(), "ContourStrikesAgain.Resources.Scripts.memberPropertyMapper.js"));


            if (!string.IsNullOrEmpty(_value)) {
                string id = _value.Split('|')[0];
                int _id = 0;

                if (int.TryParse(id, out _id))
                    picker.SelectedValue = id.Trim();

            }

            if (picker.SelectedIndex > 0)
                CreateMappers();
        }

        void picker_SelectedIndexChanged(object sender, EventArgs e) {
            CreateMappers();
        }

        private void CreateMappers()
        {
            p_items.Controls.Clear();
            p_items.Visible = false;

            int doctypeId = 0;
            string dt = picker.SelectedValue;

            if (int.TryParse(dt, out doctypeId))
            {
                MemberType memtype = new MemberType(doctypeId);

                p_items.Visible = true;

                Literal header = new Literal();
                header.Text = "<h4>Map member fields</h4>";
                p_items.Controls.Add(header);
              


                foreach (string defaultProp in "name,login,email,password".Split(','))
                {
                    Panel pl = new Panel();
                    pl.CssClass = "field";
                    pl.ID = "panel_" + defaultProp;
                    pl.CssClass = "docmapping";

                    Label l = new Label();
                    l.Text = defaultProp;
                    l.ID = "label_" + defaultProp;
                    l.AssociatedControlID = "ddl_" + defaultProp;

                    DropDownList d = new DropDownList();
                    d.ID = "ddl_" + defaultProp;
                    d.DataSource = m_recordFields;
                    d.DataTextField = "value";
                    d.DataValueField = "key";
                    d.DataBind();


                    d.Attributes.Add("onchange", "pickfield(this);");
                    d.Items.Insert(0, new ListItem("Choose...", ""));
                    d.Items.Add(new ListItem("...or set a static value", "__setValue"));

                    TextBox tb_name = new TextBox();
                    tb_name.ID = "tb_" + defaultProp;
                    tb_name.CssClass = "guiInputText guiInputStandardSize";
                    tb_name.Style.Add("display", "none");

                    m_fields.Add("__default" + defaultProp, d);
                    m_texts.Add("__default" + defaultProp, tb_name);

                    if (_valueArray.ContainsKey("__default" + defaultProp))
                    {
                        tb_name.Text = _valueArray["__default" + defaultProp][0];
                        d.SelectedValue = _valueArray["__default" + defaultProp][1];
                    }

                    if (!string.IsNullOrEmpty(tb_name.Text))
                    {
                        tb_name.Style.Add("display", "inline");
                        d.Style.Add("display", "none");
                    }

                    pl.Controls.Add(l);
                    pl.Controls.Add(tb_name);
                    pl.Controls.Add(d);

                    p_items.Controls.Add(pl);
                }
              
               
                foreach (PropertyType pt in memtype.PropertyTypes)
                {
                    Panel pl = new Panel();
                    pl.CssClass = "field";
                    pl.ID = "panel_" + pt.Id.ToString();
                    pl.CssClass = "docmapping";

                    TextBox tb = new TextBox();
                    tb.ID = "tb_" + pt.Id.ToString();
                    tb.CssClass = "guiInputText guiInputStandardSize";
                    tb.Style.Add("display", "none");
                    
                    DropDownList dd = new DropDownList();
                    dd.Attributes.Add("onchange", "pickfield(this);");
                    dd.ID = "dd_" + pt.Id.ToString();
                    dd.DataSource = m_recordFields;
                    dd.DataTextField = "value";
                    dd.DataValueField = "key";
                    dd.DataBind();

                    dd.Items.Insert(0, new ListItem("Choose...", ""));
                    dd.Items.Add(new ListItem("...or set a static value", "__setValue"));

                    m_fields.Add(pt.Alias, dd);
                    m_texts.Add(pt.Alias.ToString(), tb);

                    if (_valueArray.ContainsKey(pt.Alias.Trim())) {
                        tb.Text = _valueArray[pt.Alias.Trim()][0];
                        dd.SelectedValue = _valueArray[pt.Alias.Trim()][1];
                    }

                    if(!string.IsNullOrEmpty(tb.Text)){
                        tb.Style.Add("display", "inline");
                        dd.Style.Add("display", "none");
                    }

                    Label l = new Label();
                    l.Text = pt.Name;
                    l.ID = "label_" + pt.Id.ToString();
                    l.AssociatedControlID = "dd_" + pt.Id.ToString();

                    pl.Controls.Add(l);
                    pl.Controls.Add(tb);
                    pl.Controls.Add(dd);

                    p_items.Controls.Add(pl);
                }


            }

        }

    }
}